package com.rednose.videoplayer.utils;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class UserDatabaseHelper extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "users.db";
    private static final int DATABASE_VERSION = 2;
    // 单例实例
    private static UserDatabaseHelper instance;
//    public UserDatabaseHelper(Context context) {
//        super(context, DATABASE_NAME, null, DATABASE_VERSION);
//    }
    // 私有构造函数
    private UserDatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    // 获取单例实例的方法
    public static synchronized UserDatabaseHelper getInstance(Context context) {
        if (instance == null) {
            instance = new UserDatabaseHelper(context.getApplicationContext());
        }
        return instance;
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_TABLE_USERS = "CREATE TABLE Users (" +
                "userID INTEGER PRIMARY KEY AUTOINCREMENT, " +
                "username TEXT NOT NULL UNIQUE, " +
                "passwordHash TEXT NOT NULL);";
        String CREATE_TABLE_LISTVIDEO = "CREATE TABLE ListVideo (" +
                "mediaID INTEGER NOT NULL, " +
                "userID INTEGER NOT NULL, " +
                "position INTEGER, " +
                "PRIMARY KEY (mediaID, userID), " +
                "FOREIGN KEY (userID) REFERENCES Users(userID) ON DELETE CASCADE);";
        db.execSQL(CREATE_TABLE_USERS);
        db.execSQL(CREATE_TABLE_LISTVIDEO);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // 如果旧版本小于新版本，执行升级逻辑
        if (oldVersion < newVersion) {
            // 删除旧的 Users 表
            db.execSQL("DROP TABLE IF EXISTS Users");

            // 重新创建 Users 表
            String CREATE_TABLE_USERS = "CREATE TABLE Users (" +
                    "userID INTEGER PRIMARY KEY AUTOINCREMENT, " +
                    "username TEXT NOT NULL UNIQUE, " +
                    "passwordHash TEXT NOT NULL);";
            db.execSQL(CREATE_TABLE_USERS);

            // 如果新版本中包含了 ListVideo 表，则创建它
            if (newVersion >= 2) { // 在版本2中引入了ListVideo表
                String CREATE_TABLE_LISTVIDEO = "CREATE TABLE ListVideo (" +
                        "mediaID INTEGER NOT NULL, " +
                        "userID INTEGER NOT NULL, " +
                        "position INTEGER, " +
                        "PRIMARY KEY (mediaID, userID), " +
                        "FOREIGN KEY (userID) REFERENCES Users(userID) ON DELETE CASCADE);";
                db.execSQL(CREATE_TABLE_LISTVIDEO);
            }
        }
    }

}